//
//  StoreSearchViewController.m
//  Manager
//
//  Created by Mr.Lee on 2018/6/1.
//  Copyright © 2018年 Reabam. All rights reserved.
//

#import "StoreSearchViewController.h"
#import "LoginViewController.h"
#import "UIButton+WebCache.h"
#import "RDVTabBarController.h"
#import "MJRefresh.h"
#import "ShopKeepingCell.h"
#import "StaffCompListModel.h"
#import "TSFooterRefresh.h"
#import "TSHeaderRefresh.h"
#import "ClerkManagerViewController.h"


@interface StoreSearchViewController ()<UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource>
{
    UITextField *searchTextField;
    UIView *myToolBar;
    NSMutableArray*modelArray;
    int pageNumber;
    NSString *result;
    NSString*TotalCount;
    UITableView *table;
    UIView*noDataView;
}
@property (nonatomic, weak) UILabel *headerTitleLabel;

@end

@implementation StoreSearchViewController

- (void)BackAction:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden=YES;
    [searchTextField becomeFirstResponder];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =[UIColor whiteColor];
    modelArray = [NSMutableArray array];
    [self setUpTopView];
    [self setUpTabelList];
}


- (void)setUpTopView{
    UIView *topViewP = [[UIView alloc] init];
    topViewP.frame = CGRectMake(0, 0, ScreenWidth, StatusBarAndNavigationBarHeight);
    topViewP.backgroundColor = lanse;
    [self.view addSubview:topViewP];
    
    UIView *topView = [[UIView alloc] init];
    topView.frame = CGRectMake(0, StatusBarHeight, ScreenWidth, 44);
    topView.backgroundColor = lanse;
    [topViewP addSubview:topView];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    UIImage *tinted = [backImage rt_tintedImageWithColor:[UIColor whiteColor]];
    
    UIButton* backButton= [[UIButton alloc] init];
    backButton.frame = CGRectMake(0, 0, 58, 44);
    [backButton setImage:tinted forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:backButton];
    
    UIView *topLineView = [[UIView alloc] init];
    topLineView.frame = CGRectMake(0, topView.height-0.5, ScreenWidth, 1);
    topLineView.backgroundColor = [UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0];
//    [topView addSubview:topLineView];
    
    myToolBar=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, viewheight)];
    myToolBar.backgroundColor=jianpancolor;
    UIButton*  tubtnDone=[[UIButton alloc]initWithFrame:CGRectMake(logoX,logoY, logoheight, logowidth)];
    [tubtnDone setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [tubtnDone addTarget:self action:@selector(OnTapDone1) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:tubtnDone];
    UIButton*btnDone111=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width - 55, 12, 40, 16)];
    [btnDone111 setTitle:@"搜索" forState:UIControlStateNormal];
    [btnDone111 setTitleColor:jianpancolor1 forState:UIControlStateNormal];
    btnDone111 .titleLabel .font=[UIFont systemFontOfSize:keyboardFot];
    [btnDone111 addTarget:self action:@selector(OnTapDone1) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:btnDone111];
    myToolBar.alpha=alp;
    UIButton* dabtn=[[UIButton alloc]initWithFrame:CGRectMake(myToolBar.frame.size.width-60, 0, 60, 40)];
    [dabtn addTarget:self action:@selector(OnTapDone1) forControlEvents:UIControlEventTouchUpInside];
    [myToolBar addSubview:dabtn];
    
    UIView *sousuoView=[[UIView alloc]initWithFrame:CGRectMake(backButton.right-5, (topView.height- 65/2)*0.5, ScreenWidth- backButton.width-15+5, 65/2)];
    sousuoView.backgroundColor= [UIColor colorWithRed:82/255.0 green:180/255.0 blue:236/255.0 alpha:0.36];
    sousuoView.layer.cornerRadius = 15.0;
    sousuoView.layer.masksToBounds = YES;
    [topView addSubview:sousuoView];
    
    UIImage* fangdajing = [UIImage imageNamed:@"sousuo"];
    UIImage *fangdajingNew = [fangdajing rt_tintedImageWithColor:[UIColor colorWithHexString:@"92cff3"]];
    UIButton *screenBtnIM = [[UIButton alloc] initWithFrame:CGRectMake(10, 4, 50/2, 50/2)];
    [screenBtnIM setImage:fangdajingNew forState:UIControlStateNormal];
    [sousuoView addSubview:screenBtnIM];
    
    searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(screenBtnIM.right+5, 1, sousuoView.width-screenBtnIM.right -10,65/2)];
    [searchTextField setBorderStyle:UITextBorderStyleNone]; //外框类型
    searchTextField.placeholder = @"请输入商户名搜索"; //默认显示的字
    searchTextField.font = [UIFont systemFontOfSize:14.0];
    [searchTextField setValue:[UIColor colorWithHexString:@"92cff3"] forKeyPath:@"_placeholderLabel.textColor"];
    searchTextField.tag=22;
    searchTextField.returnKeyType = UIReturnKeySearch;
    searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing; //编辑时会出现个修改X
    searchTextField.delegate = self;
    searchTextField.tintColor = [UIColor colorWithHexString:@"92cff3"];//光标颜色;
    searchTextField.textColor = [UIColor whiteColor];   // 输入文字颜色
    searchTextField.inputAccessoryView = myToolBar;
    [searchTextField addTarget:self action:@selector(inputFiled:) forControlEvents:UIControlEventEditingChanged];
    [sousuoView addSubview:searchTextField];
}

- (void)setUpTabelList {
    
    UIView *headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 64, ScreenWidth, 40);
    headerView.backgroundColor = lanse1;
    UILabel *headerTitleLabel = [[UILabel alloc] init];
    self.headerTitleLabel = headerTitleLabel;
    headerTitleLabel.frame = CGRectMake(10, 0, ScreenWidth-30, 40);
    headerTitleLabel.font = [UIFont systemFontOfSize:14.0];
    headerTitleLabel.textColor = [UIColor colorWithHexString:@"0880c6"];
    [headerView addSubview:headerTitleLabel];
//    [self.view addSubview:headerView];
    
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, StatusBarAndNavigationBarHeight, ScreenWidth, ScreenHeight- StatusBarAndNavigationBarHeight) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    table.separatorStyle=UITableViewCellSeparatorStyleNone;
    [self.view addSubview:table];
    
    UIView*foot=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 64)];
    foot.backgroundColor=[UIColor whiteColor];
    table.tableFooterView=foot;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    [searchTextField resignFirstResponder];
}
- (BOOL)textFieldShouldClear:(UITextField *)textField{
    [searchTextField resignFirstResponder];
    searchTextField.text = nil;
    [modelArray removeAllObjects];
    [table reloadData];
    return YES;
}
- (void)inputFiled:(UITextField *)tf{
    if (tf.text.length == 0) {
        NSLog(@"---");
//        [searchTextField resignFirstResponder];
        searchTextField.text = nil;
        [modelArray removeAllObjects];
        [table reloadData];
    }
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [searchTextField resignFirstResponder];
    if (textField.text.length >0) {
        NSString *serchWord = textField.text;
        [self requestCompanyWithKeyWord:serchWord];
    }else{
        searchTextField.text = nil;
        [modelArray removeAllObjects];
        [table reloadData];
    }
    
    return YES;
    
}

-(void)OnTapDone1{
    [searchTextField resignFirstResponder];
    if (searchTextField.text.length >0) {
        NSString *serchWord = searchTextField.text;
        [self requestCompanyWithKeyWord:serchWord];
    }
}

//// 刷新
//- (void)setUpRefresh {
//    table.mj_header = [TSHeaderRefresh headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
//    table.mj_footer = [TSFooterRefresh footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreProductList)];
//
//}
//// 下拉刷新
//- (void)headerRefresh {
//    [self requestData];
//}



-(void)requestCompanyWithKeyWord:(NSString *)keyWord{
    
    [modelArray removeAllObjects];
    NSString *Token = [UserDefaults objectForKey:@"tokenId"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:Token forKey:@"tokenId"];
    [params setValue:keyWord forKey:@"sword"];
    NSLog(@"-----params---- %@", params);
    [MBProgressHUD showIndeterminateHudSub:@"加载中，请稍候。。。" delay:30 view:self.view];
    [HttpRequest requestData:@"manage/findCompanyList" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
        NSLog(@"OrderListllllll====%@",severDataDict.dataDict);
        if (isSuccess) {
           
            [MBProgressHUD hideProgressHUDInternal:self.view];
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                NSMutableArray *dataArr = [severDataDict.dataDict objectForKey:@"compDatas"];
                if (dataArr.count > 0) {
                    for (NSDictionary* dicc in dataArr ){
                        StaffCompListModel *model = [StaffCompListModel mj_objectWithKeyValues:dicc];
                        [modelArray addObject:model];
                    }
                    [table reloadData];
                    
                    // 获取总数
                    NSString *compQty=[severDataDict.dataDict objectForKey:@"compQty"];
                    self.headerTitleLabel.text = [NSString stringWithFormat:@"共 %@ 个商户", compQty];
                    
                }
                
            } else {
                [MBProgressHUD hideProgressHUDInternal:self.view];
                NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
                [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
                
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
                    LoginViewController *loginVC = [[LoginViewController alloc] init];
                    [self.navigationController pushViewController:loginVC animated:YES];
                }
            }
        } else {
            [MBProgressHUD hideProgressHUDInternal:self.view];
            [MBProgressHUD showTextHudSub:severDataDict.resultStr view:self.view];
        }
    }];
    
    
//    pageNumber=1;
//    [noDataView removeFromSuperview];
//    [modelArray removeAllObjects];
//    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//    NSString* Token = [user objectForKey:@"tokenId"];
//    NSMutableDictionary *param = [NSMutableDictionary new];
//    [param setValue:Token forKey:@"tokenId"];
//    [param setValue:@"1" forKey:@"pageIndex"];
//    [param setValue:@"20" forKey:@"pageSize"];
//    [param setValue:keyword forKey:@"keyword"];
//    NSLog(@"%@", param);
//    [MBProgressHUD showIndeterminateHudSub:@"加载中，请稍候。。。" delay:30 view:self.view];
//    [HttpRequest requestData:@"/Discover/Household/List" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
//        if (isSuccess) {
//            [modelArray removeAllObjects];
//            NSLog(@"====%@",severDataDict.dataDict);
//            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
//                [MBProgressHUD hideProgressHUDInternal:self.view];
//                NSMutableArray* arrr=[[NSMutableArray alloc]init];
//                TotalCount=[severDataDict.dataDict objectForKey:@"TotalCount"];
//                arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
//                for (NSDictionary* dicc in arrr ) {
//
//                    DiscoverListModel *model =[DiscoverListModel  mj_objectWithKeyValues:dicc];
//                    [modelArray addObject:model];
//                }
//
//                if (arrr.count == 0) {
//                    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
//                    if ([[user objectForKey:@"userStatus"] isEqualToString:@"W"]) {
//
//                    }else{
//
//                        noDataView=[[UIView alloc]initWithFrame:CGRectMake(0, ScreenHeight/2-50, ScreenWidth, 80)];
//                        [self.view addSubview:noDataView];
//                        UIImageView*noImage=[[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth/2-47, 0, 94, 51)];
//                        noImage.image=[UIImage imageNamed:@"meiyoushuju"];
//                        [noDataView addSubview:noImage];
//                        UILabel*noLabel=[[UILabel alloc]initWithFrame:CGRectMake(0,65, ScreenWidth, 14)];
//                        noLabel.text=@"没有列表数据，赶紧去添加！";
//                        noLabel.textColor=zhonghuiColor; noLabel.font=[UIFont systemFontOfSize:14];
//                        noLabel.textAlignment=NSTextAlignmentCenter;
//                        [noDataView addSubview:noLabel];
//
//                    }
//                }
//
//                [table reloadData];
//
//            }else{
//                [MBProgressHUD hideProgressHUDInternal:self.view];
//                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==9999) {
//                    LoginViewController *loginVC=[[LoginViewController alloc] init];//2.0{9个参数 少2个}
//                    [self.navigationController pushViewController:loginVC animated:YES];
//                }
//            }
//
//        } else {
//            [MBProgressHUD hideProgressHUDInternal:self.view];
//        }
//
//    }];
    
}

// 上拉刷新
//- (void)loadMoreProductList{
//
//    if (TotalCount.intValue/20>=pageNumber) {
//        pageNumber++;
//        NSUserDefaults *user1 = [NSUserDefaults standardUserDefaults];
//        NSString* tokenId = [user1 objectForKey:@"tokenId"];
//        NSMutableDictionary *params = [NSMutableDictionary new];
//        [params setValue:tokenId forKey:@"tokenId"];
//        [params setValue:[NSString stringWithFormat:@"%d" ,pageNumber] forKey:@"pageIndex"];
//        [params setValue:@"30" forKey:@"pageSize"];
//        //            [params setValue:self.dhTypeCode forKey:@"dhTypeCode"];
//        [params setValue:keyword forKey:@"keyword"];
//        [MBProgressHUD showIndeterminateHudSub:@"加载中，请稍候。。。" delay:30 view:self.view];
//        [HttpRequest requestData:@"/Discover/Household/List" params:params success:^(BOOL isSuccess, SeverData *severDataDict) {
//            if (isSuccess) {
//                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
//                    [MBProgressHUD hideProgressHUDInternal:self.view];
//                    NSMutableArray* arrr=[[NSMutableArray alloc]init];
//                    arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
//                    for (NSDictionary* dicc in arrr ) {
//                        DiscoverListModel *model =[DiscoverListModel  mj_objectWithKeyValues:dicc];
//                        [modelArray addObject:model];
//                    }
//                    [table reloadData];
//
//                    TotalCount=[severDataDict.dataDict objectForKey:@"TotalCount"];
//                    if (TotalCount.intValue < 10) {
//                        [table.mj_footer endRefreshingWithNoMoreData];
//                    } else if(TotalCount.intValue >10){
//                        [table.mj_footer resetNoMoreData];
//                    }
//                }else {
//                    NSString *requestResultStr=[severDataDict.dataDict objectForKey:@"ResultString"];
//                    [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
//                }
//
//            } else {
//                [MBProgressHUD hideProgressHUDInternal:self.view];
//                [MBProgressHUD showTextHudSub:severDataDict.resultStr view:self.view];
//            }
//        }];
//    }else{
//        NSString *requestResultStr=@"没有更多数据了！";
//        [MBProgressHUD showTextHudSub:requestResultStr view:self.view];
//        [table.mj_footer endRefreshingWithNoMoreData];
//
//    }
//}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return modelArray.count;
}
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return  109;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    StaffCompListModel *model = modelArray[indexPath.row];
    static NSString *CellIdentifier = @"cell";
    ShopKeepingCell *cell = ( ShopKeepingCell *)[tableView dequeueReusableCellWithIdentifier: CellIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"ShopKeepingCell" owner:nil options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = model;
    return cell;
}

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    StaffCompListModel *model = modelArray[indexPath.row];
    ClerkManagerViewController *storeInforVC = [[ClerkManagerViewController alloc] init];
    storeInforVC.companyId = model.companyId;
    storeInforVC.titleName = model.companyName;
    storeInforVC.view.backgroundColor = [UIColor whiteColor];
    [self.navigationController pushViewController:storeInforVC animated:YES];
    
}


@end
